//
//  FingerVerifyVC.m
//  yunbao
//
//  Created by 金牛 on 2017/9/9.
//  Copyright © 2017年 金牛. All rights reserved.
//

#import "FingerVerifyVC.h"
#import <LocalAuthentication/LocalAuthentication.h>
#import "NewTabbarVC.h"

@interface FingerVerifyVC ()

@end

@implementation FingerVerifyVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"请输入指纹";
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBarHidden = YES;
    
    UIImageView *imageView = [UIImageView new];
    NSDictionary *infoPlist = [[NSBundle mainBundle] infoDictionary];
    NSString *icon = [[infoPlist valueForKeyPath:@"CFBundleIcons.CFBundlePrimaryIcon.CFBundleIconFiles"] lastObject];
    UIImage* image = [UIImage imageNamed:icon];
    imageView.image = image;
    [self.view addSubview:imageView];
    imageView.sd_layout.topSpaceToView(self.view, 120).centerXEqualToView(self.view).widthIs(60).heightEqualToWidth();
    UIImageView * bgView = [UIImageView new];
    bgView.image = Image(@"指纹");
    bgView.userInteractionEnabled = YES;
    [self.view addSubview:bgView];
    bgView.sd_layout.centerXEqualToView(self.view).centerYEqualToView(self.view).offset(-10).heightIs(70).widthIs(70);
    UILabel *label = [UILabel labelWithTitle:@"点击进行指纹解锁" color:[UIColor colorWithRed:0.29 green:0.53 blue:0.98 alpha:1] fontSize:14 alignment:NSTextAlignmentCenter];
    [self.view addSubview:label];
    label.sd_layout.topSpaceToView(bgView, 10).leftEqualToView(self.view).rightEqualToView(self.view).heightIs(20);
    UIButton *centerBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [centerBtn addTarget:self action:@selector(evaluateAuthenticate) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:centerBtn];
    centerBtn.sd_layout.centerYEqualToView(bgView).centerXEqualToView(bgView).widthIs(70).heightIs(100);
    [self evaluateAuthenticate];
}


- (void)evaluateAuthenticate{
    //创建LAContext
    LAContext* context = [[LAContext alloc] init];
    NSError* error = nil;
    NSString* result = @"";
    if (iPhoneX) {
        result = @"请验证已有FaceID";
    }else{
        result = @"请验证已有指纹";
    }
    //首先使用canEvaluatePolicy 判断设备支持状态
    if ([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error]) {
        //支持指纹验证
        [context evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:result reply:^(BOOL success, NSError *error) {
            if (success) {
                //验证成功，主线程处理UI
                NSUserDefaults * def = [NSUserDefaults standardUserDefaults];
                if (iPhoneX) {
                    [def setObject:@"YES" forKey:@"faceidstate"];
                }else{
                    [def setObject:@"YES" forKey:@"fingerstate"];
                }
                dispatch_async(dispatch_get_main_queue(), ^{
                    [UIApplication sharedApplication].keyWindow.rootViewController = [[NewTabbarVC alloc] init];
                });
            }else{
                NSLog(@"%@",error.localizedDescription);
                switch (error.code) {
                    case LAErrorSystemCancel:{
                    }break;
                    case LAErrorUserCancel:{
                    }break;
                    case LAErrorAuthenticationFailed:{
                        dispatch_async(dispatch_get_main_queue(), ^{
                            //授权失败
                            [Mytools warnText:@"指纹不匹配" status:Error];
                        });
                    }break;
                    case LAErrorPasscodeNotSet:{
                        //系统未设置密码
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [Mytools warnText:@"系统未设置密码" status:Error];
                        });
                    }break;
                    case LAErrorTouchIDNotAvailable:{
                        //设备Touch ID不可用，例如未打开
                        dispatch_async(dispatch_get_main_queue(), ^{
                            if (iPhoneX) {
                                [Mytools warnText:@"Face ID不可用，请检查是否开启" status:Error];
                            }else{
                                [Mytools warnText:@"Touch ID不可用，请检查是否开启" status:Error];
                            }
                        });
                    }break;
                    case LAErrorTouchIDLockout:{
                        NSInteger policy = LAPolicyDeviceOwnerAuthenticationWithBiometrics;
                        if (@available(iOS 9.0, *)) {
                            policy = LAPolicyDeviceOwnerAuthentication;
                        } else {
                            // Fallback on earlier versions
                        }
                        [context evaluatePolicy:policy localizedReason:@"通过Home键验证已有手机指纹"reply:^(BOOL success, NSError * _Nullable error) {
                            
                        }];
                    }break;
                    case LAErrorTouchIDNotEnrolled:{
                        //设备Touch ID不可用，用户未录入
                        dispatch_async(dispatch_get_main_queue(), ^{
                            if (iPhoneX) {
                                [Mytools warnText:@"您尚未录入Face ID" status:Error];
                            }else{
                                [Mytools warnText:@"您尚未录入Touch ID" status:Error];
                            }
                        });
                    }break;
                    case LAErrorUserFallback:{
                        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                            //用户选择输入密码，切换主线程处理
                            [Mytools deleteAllUserDefaules];
                            NSUserDefaults *defatluts = [NSUserDefaults standardUserDefaults];
                            [defatluts removeObjectForKey:@"token"];
                            [defatluts removeObjectForKey:@"password"];
                            [defatluts synchronize];
                            dispatch_async(dispatch_get_main_queue(), ^{
                                [UIApplication sharedApplication].keyWindow.rootViewController = [NewTabbarVC new];
                            });
                        }];
                    }break;
                    default:{
                        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                            //其他情况，切换主线程处理
                        }];
                    }break;
                }
            }
        }];
    }else{
        //不支持指纹识别，LOG出错误详情
        NSLog(@"不支持指纹识别");
        switch (error.code) {
            case LAErrorTouchIDNotEnrolled:{
                NSLog(@"TouchID is not enrolled");
            }break;
            case LAErrorPasscodeNotSet:{
                NSLog(@"A passcode has not been set");
            }break;
            default:{
                NSLog(@"TouchID not available");
            }break;
        }
//        NSLog(@"%@",error.localizedDescription);
    }
}

@end
